package com.lepu.app.fun.chat.business.album;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.app.application.MyApplication;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.bean.ChatMessage;
import com.lepu.app.fun.chat.business.chatcore.ChatDAO;
import com.lepu.app.fun.chat.controller.base.AbsBaseFragment;
import com.lepu.app.fun.chat.util.StorageManager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;
import java.util.List;

import common.db.Constants;
import view.AnimationImageView;
import view.OnZoomImageClickCallBack;

/**
 * Created by lepu on 2014/12/25.
 */
public class PhotoDisplayFragment extends AbsBaseFragment {
    View view;
    AnimationImageView imageView;
    ProgressBar progressBar;
    String imagePath;
    ImageLoader imageLoader = ImageLoader.getInstance();
    boolean isAttachFile = false;
    String objectId = "";
    boolean slide = false;
    List<String> images;
    ViewPager pager;
    ImagePagerAdapter pagerAdapter;
    int currentPos = 0;
    private ProgressBar progressBarMain;
    private DisplayImageOptions displayImageOptions;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle.containsKey(Constants.Chat.CHAT_IMAGE_ATTACHFILE)) {
            isAttachFile = true;
            imagePath = bundle.getString(Constants.Chat.CHAT_IMAGE_ATTACHFILE);
            imagePath = StorageManager.getInstance().getFormatFileName(imagePath);
        } else {
            isAttachFile = false;
            imagePath = bundle.getString(Constants.Chat.CHAT_IMAGE_OBJECT_ID);
            // imagePath = AppCommonService.getInstance().getObjectDownloadUrl(imagePath);
        }

        if (bundle.containsKey(Constants.Chat.CHAT_MESSAGE)) {
            slide = true;
            long sessionId = Long.parseLong(bundle.getString(Constants.Chat.CHAT_SESSION));
            List<ChatMessage> chatMessages = ChatDAO.getInstance().getChatMessages(sessionId);
            images = getImagesPath(chatMessages);
            //// TODO: 2015/11/14  修改一次
            if (images == null) { //认为是漂流瓶
                try {
                    String bottleUrl = "";
                    if (TextUtils.isEmpty(imagePath)) {
                        bottleUrl = bundle.getString(Constants.Chat.CHAT_IMAGE_OBJECT_ID);
                    } else {
                        bottleUrl = imagePath;
                    }

                    images = new ArrayList<String>();
                    images.add(bottleUrl);
                } catch (Exception e) {
                    images = null;
                    return;
                }
            }
            if (images != null) {
                currentPos = getCurrentPos(images);
            }
        } else {
            images = new ArrayList<String>();
            images.add(imagePath);
            if (imagePath != null) {
                currentPos = getCurrentPos(images);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.chat_fragment_single_photo, container, false);
        progressBarMain = (ProgressBar) view.findViewById(R.id.loading);
        RelativeLayout layoutBackground = (RelativeLayout) view.findViewById(R.id.layout_bg);
        layoutBackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                performBack();
            }
        });
        pager = (ViewPager) view.findViewById(R.id.viewpager_photo);
        pagerAdapter = new ImagePagerAdapter();
        pager.setAdapter(pagerAdapter);
        pager.setCurrentItem(currentPos);
        pager.setEnabled(true);
        return view;
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private LayoutInflater inflater;

        ImagePagerAdapter() {
            inflater = getActivity().getLayoutInflater();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return images == null ? 0 : images.size();
        }

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {
            View imageLayout = inflater.inflate(R.layout.chat_item_photo_preview_pager, view, false);
            final AnimationImageView imageView = (AnimationImageView) imageLayout.findViewById(R.id.imgview_preview);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
            String imagePath = images.get(position);
            if (imagePath != null && !TextUtils.isEmpty("imagePath")) {
//                String url = StorageManager.getInstance().getFormatFileName(imagePath);
                // imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
//                ImageLoaderUtil.getInstance().loadImage(imageLoader, imagePath, imageView, MyApplication.getInstance().getDisplayImgOptions(),
//                        new ImageLoadingListener(),new SimpleImageLoadingListener(){
//
//                            @Override
//                            public void onLoadingComplete(String imageUri, View view,
//                                                          Bitmap loadedImage) {
//                                super.onLoadingComplete(imageUri, view, loadedImage);
//                                imageView.setImageBitmap(loadedImage);
//                            }
//
//                        }
//                );

                ImageLoader.getInstance().loadImage(imagePath,getDisplayImgOptions(), new SimpleImageLoadingListener() {

                    @Override
                    public void onLoadingComplete(String imageUri, View view,
                                                  Bitmap loadedImage) {
                        super.onLoadingComplete(imageUri, view, loadedImage);
                        imageView.setImageBitmap(loadedImage);
                        if (progressBarMain != null)
                            progressBarMain.setVisibility(View.GONE);
                        LogUtilBase.LogD(PhotoDisplayFragment.class.getSimpleName(), "close progress");
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        super.onLoadingFailed(imageUri, view, failReason);
                        progressBarMain.setVisibility(View.GONE);
                        UIHelper.showToast(getActivity(), "图片加载未成功！");
                    }
                });
//                new ImageLoadingProgressListener() {
//                    @Override
//                    public void onProgressUpdate(String imageUri, View view, int current, int total) {
//                        spinner.setVisibility(View.VISIBLE);
//                        spinner.setProgress(Math.round(100.0f * current / total));
//                        if (current == total) {
//                            spinner.setVisibility(View.INVISIBLE);
//                        }
//                    }
//                }
                ///////////////////
//                new ImageLoaderUtil.SimpleImageLoadingProgressListener(spinner) {
//                    @Override
//                    public void onProgressUpdate(String imageUri, View view, int current, int total) {
//                        spinner.setVisibility(View.VISIBLE);
//                        spinner.setProgress(Math.round(100.0f * current / total));
//                        if (current == total) {
//                            spinner.setVisibility(View.INVISIBLE);
//                        }
//                    }
//
//                }
            } else {
                //// TODO: 2015/10/13  去掉客户端类型判断
                int drawResource = R.drawable.default_heade;
                imageLoader.displayImage("drawable://" + drawResource, imageView,getDisplayImgOptions());
            }

            view.addView(imageLayout);
            imageView.setClickCallBack(new OnZoomImageClickCallBack() {
                @Override
                public void OnLongClickResponse(PointF point) {
                }

                public void OnDoubleClickResponse(PointF point) {
                    float magfactor = 1.6f;
                    float float_epsilon = 1e-3f;
                    float viewwidth = imageView.getWidth();
                    float viewheight = imageView.getHeight();
                    float imagewidth = imageView.getDrawable().getBounds().width();
                    float imageheight = imageView.getDrawable().getBounds().height();

                    Matrix matrix = new Matrix();
                    matrix.set(imageView.getImageMatrix());
                    float[] values = new float[9];
                    matrix.getValues(values);

                    float ratiox = viewwidth / imagewidth;
                    float ratioy = viewheight / imageheight;
                    float minratio = ratiox < ratioy ? ratiox : ratioy;
                    float transx, transy;
                    //回原图
                    if (values[0] > (minratio + float_epsilon)) {
                        if (ratiox < ratioy) {
                            transx = 0;
                            transy = (viewheight - ratiox * imageheight) / 2;
                        } else {
                            transx = (viewwidth - ratioy * imagewidth) / 2;
                            transy = 0;
                        }
                        values[0] = values[4] = minratio;
                        values[2] = transx;
                        values[5] = transy;
                        matrix.setValues(values);
                        imageView.EnableAnimation(imageView.getImageMatrix(), matrix, 200);
                    } else {//放大
                        matrix.postScale(magfactor, magfactor, point.x, point.y);
                        imageView.EnableAnimation(imageView.getImageMatrix(), matrix, 200);
                    }
                }

                public void OnSingleTapConfirmed(PointF point) {
                    performBack();
                }
            });
            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

    }

    private class ImageLoadingListener extends SimpleImageLoadingListener {

    }


    public List<String> getImagesPath(List<ChatMessage> chatMessages) {
        ArrayList<String> pathList = new ArrayList<String>();
        if (chatMessages == null || chatMessages.size() <= 0) {
            return null;
        }
        for (int i = 0; i < chatMessages.size(); i++) {
            if (chatMessages.get(i).getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_IMAGE) {
                if (chatMessages.get(i).getDirection() == Constants.Chat.CHAT_DIRECTION_RECEIVE) {
//                    String objectId = chatMessages.get(i).getMedia().getObjectId();
                    String largeImageId = chatMessages.get(i).getMedia().getLargeImageId();
                    String objectId = largeImageId;
//                    if (objectId.equals(largeImageId)) {
//                        String url = AppCommonService.getInstance().getObjectDownloadUrl(largeImageId);
//                        pathList.add(url);
//                    } else {
//                    String url = AppCommonService.getInstance().getObjectDownloadUrl(objectId);
                    pathList.add(objectId);
//                    }
                } else {
                    String url = "file://" + chatMessages.get(i).getMedia().getFullName();
                    pathList.add(url);
                }
            }
        }
        return pathList;
    }

    private int getCurrentPos(List<String> pathList) {
        int position = -1;
        if (pathList == null || pathList.size() <= 0) {
            return position;
        }
        for (int i = 0; i < pathList.size(); i++) {
            if (pathList.get(i).equals(imagePath)) {
                position = i;
                break;
            }
        }
        return position;
    }

    public DisplayImageOptions getDisplayImgOptions() {
        if (displayImageOptions == null) {
            displayImageOptions = new DisplayImageOptions.Builder().
                    considerExifParams(true)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2).
                            build();
        }
        return displayImageOptions;
    }

}
